package com.daxia.ogmall.web.controller.admin;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daxia.ogmall.common.DesignStatus;
import com.daxia.ogmall.common.DesignType;
import com.daxia.ogmall.common.UserType;
import com.daxia.ogmall.dto.DesignDTO;
import com.daxia.ogmall.dto.DesignerDTO;
import com.daxia.ogmall.dto.JsonResultDTO;
import com.daxia.ogmall.dto.UserDTO;
import com.daxia.ogmall.model.Designer;
import com.daxia.ogmall.model.User;
import com.daxia.ogmall.service.DesignService;
import com.daxia.ogmall.support.Page;
import com.daxia.ogmall.web.controller.BaseController;

@Controller
@RequestMapping(value = "/admin/design", produces="text/html;charset=UTF-8")
public class AdminDesignController extends BaseController {

	@Autowired
	private DesignService designService;

	@RequestMapping(value = "/detail")
	public String detail(Map<String, Object> map, Long id) {
		if (id != null) {
			DesignDTO dto = designService.load(id);
			map.put("n", dto);
		}
		map.put("designTypes", DesignType.values());
		UserDTO user = getCurrentUserDTO();
		if (user.getType() == UserType.Designer.getValue()) {
			map.put("isDesigner", true);
			map.put("self", user);
		}
		map.put("houseTypes", houseTypeService.findAll());
		map.put("houseStyles", houseStyleService.findAll());
		return "admin/design/design_detail";
	}
	
	@RequestMapping(value = "uploadDesign")
	public String uploadDesign() {
		
		return "admin/design/design_uploadDesign";
	}
	
	@ResponseBody
	@RequestMapping(value = "/save")
	public String save(DesignDTO dto, JsonResultDTO resultDTO, HttpServletRequest request) throws Exception {
		logger.error("content: " + dto.getContent());
		String pdf = super.saveFileAndReturnFileName(request, "pdfFile");
		if (StringUtils.isNotBlank(pdf)) {
			dto.setPdf(pdf);
		}
		User user = dto.getUser();
		DesignerDTO designerQuery = new DesignerDTO();
		User queryUser = new User();
		queryUser.setId(user.getId());
		designerQuery.setUser(queryUser);
		DesignerDTO designerDTO = designerService.findOne(designerQuery );
		Designer designer = new Designer();
		BeanUtils.copyProperties(designerDTO, designer);
		dto.setDesigner(designer);
		
		if (dto.getHouseStyle() == null && dto.getHouseStyle().getId() != null) {
			dto.setHouseStyle(null);
		}
		if (dto.getHouseType() == null) {
			dto.setHouseType(null);
		} else if (dto.getHouseType().getId() == null) {
			dto.setHouseType(null);
		}
		if (dto.getCommunityHouseType() == null) {
			dto.setCommunityHouseType(null);
		} else if (dto.getCommunityHouseType().getId() == null) {
			dto.setCommunityHouseType(null);
		}
		if (dto.getCommunity() == null) {
			dto.setCommunity(null);
		} else if (dto.getCommunity().getId() == null) {
			dto.setCommunity(null);
		}
		if (dto.getCompany() == null) {
			dto.setCompany(null);
		} else if (dto.getCompany().getId() == null) {
			dto.setCompany(null);
		}
		if (dto.getId() == null) {
			designService.create(dto);
		} else {
			DesignDTO old = designService.load(dto.getId());
			old.setUser(dto.getUser());
			old.setDesigner(dto.getDesigner());
			old.setTitle(dto.getTitle());
			old.setDetails(dto.getDetails());
			old.setType(dto.getType());
			old.setHouseType(dto.getHouseType());
			old.setHouseStyle(dto.getHouseStyle());
			old.setArea(dto.getArea());
			old.setPdf(dto.getPdf());
			old.setView3dURL(dto.getView3dURL());
			old.setVRURL(dto.getVRURL());
			old.setQRCode(dto.getQRCode());
			old.setCommunity(dto.getCommunity());
			old.setCommunityHouseType(dto.getCommunityHouseType());
			old.setTheme(dto.getTheme());
			old.setPrice(dto.getPrice());
			old.setContent(dto.getContent());
			old.setHeadImage(dto.getHeadImage());
			old.setImages(dto.getImages());
			old.setRecommend(dto.getRecommend());
			designService.updateAllFields(old);
		}
		// 更新用户置顶信息
		designerDTO.setTopDesignerImage(dto.getImages());
		designerService.updateAllFields(designerDTO);
		return okAndClose(resultDTO);
	}

	@ResponseBody
	@RequestMapping(value = "/delete") 
	public String delete(Long[] ids, JsonResultDTO resultDTO) throws IOException {
		designService.deleteByIds(ids);
		return okAndRefresh(resultDTO);
	}
	
	@RequestMapping(value = "/list")
	public String list(DesignDTO dto, Map<String, Object> map, Page page) {
		dto.setFromAdmin(true);
		if (getCurrentUserDTO().getType() == UserType.Designer.getValue()) {
			dto.setUser(getCurrentUserDTO());
		}
		/// 如果是城市运营商，只能看到自己的，或者名下的设计师的，或者名下装修公司的设计师的
		if (getCurrentUserDTO().getType() == UserType.City.getValue()) {
			dto.setCityUserId(getCurrentUserDTO().getId());
		}
		
		// 如果是装修公司，只能看到自己名下的
		if (getCurrentUserDTO().getType() == UserType.DecorateCompany.getValue()) {
			dto.setCompanyUserId(getCurrentUserDTO().getId());
		}

		List<DesignDTO> dtos = designService.find(dto, page);
		map.put("list", dtos);
		map.put("query", dto);
		map.put("designTypes", DesignType.values());
		map.put("ogSessionId", userService.getOgSessionId(getCurrentUserDTO().getId()));
		map.put("status", DesignStatus.values());
		return "admin/design/design_list";
	}
	
	@ResponseBody
	@RequestMapping(value = "/datagrid")
    public String datagrid(DesignDTO dto, Map<String, Object> map, Page page) throws Exception {
        List<DesignDTO> dtos = designService.find(dto, page);
        JSONArray jsonArray = new JSONArray();
        for (DesignDTO design : dtos) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", design.getId());
	        jsonObject.put("user.nickName", design.getUser().getNickName());    	
            jsonObject.put("title", design.getTitle());
            jsonObject.put("content", design.getContent());
	        jsonObject.put("houseType.name", design.getHouseType().getName());    	
	        jsonObject.put("houseStyle.name", design.getHouseStyle().getName());    	
            jsonObject.put("area", design.getArea());
            jsonObject.put("theme", design.getTheme());
            jsonObject.put("price", design.getPrice());
            jsonObject.put("headImage", design.getHeadImage());
            jsonObject.put("images", design.getImages());
            jsonArray.add(jsonObject);
        }
        JSONObject json = new JSONObject();
        json.put("total", page.getTotalRecords());
        json.put("rows", jsonArray);
        return json.toJSONString();
    }
	
	@RequestMapping("auth")
	public String auth(Long id, Map<String, Object> map) throws Exception {
		map.put("n", designService.load(id));
		return "admin/design/design_auth";
	}
	
	@ResponseBody
	@RequestMapping("saveAuth")
	public String saveAuth(Long id, Integer status, Map<String, Object> map) throws Exception {
		DesignDTO d = designService.load(id);
		d.setStatus(status);
		designService.updateAllFields(d);
		return ok();
	}
}
